package com.jing21.learn.tests.crawler.resolver;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import java.util.List;
import java.util.Optional;

/**
 * Created by 郑靖 on 2017/10/8.
 */
@Slf4j
public abstract class AbstractDomainResolver<T> {

    /**
     * 解析类型
     */
    protected Target target = Target.BODY;


    enum Target {
        BODY,
        Head,
        HTML
    }

    /**
     * 解析一个文档
     * @param element 文档
     * @return
     */
    protected  abstract List<T> resolution(Element element);


    List<T> execute(String uri) {
        try {
           return Optional.ofNullable(Jsoup.connect(uri).get())
                    .map(document -> {
                        switch (target) {
                            case BODY:
                                return document.body();
                            case Head:
                                return document.head();
                            case HTML:
                                return document;
                            default:
                                throw new RuntimeException("不支持的解析类型");
                        }
                    }).map(this::resolution).get();

        } catch (Exception e) {
            log.error("解析出错:" + uri, e);
        }
        return null;
    }
}
